package com.moyun.zbmy.zizhou.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.moyun.zbmy.zizhou.application.Cache;
import com.moyun.zbmy.zizhou.http.AbsListNetCallback;
import com.ruihang.generalibrary.utils.ListUtils;
import com.moyun.zbmy.zizhou.R;
import com.moyun.zbmy.zizhou.application.Constances;
import com.moyun.zbmy.zizhou.base.BaseAccountActivity;
import com.moyun.zbmy.zizhou.beans.AccountBean;
import com.moyun.zbmy.zizhou.beans.AccountTagBean;
import com.moyun.zbmy.zizhou.http.AbsNetCallBack;
import com.moyun.zbmy.zizhou.http.NetUtils;
import com.moyun.zbmy.zizhou.ui.adapter.AccountAdapter;
import com.moyun.zbmy.zizhou.ui.adapter.AccountTypeAdapter;
import com.moyun.zbmy.zizhou.ui.util.IListShowData;
import com.moyun.zbmy.zizhou.ui.utils.DataUtils;
import com.moyun.zbmy.zizhou.ui.utils.TitleUtils;
import com.moyun.zbmy.zizhou.utils.ListTypeUtils;
import com.moyun.zbmy.zizhou.utils.UserManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * 更多公众号
 */
public class MoreAccountActivity extends BaseAccountActivity implements CanRefreshLayout.OnRefreshListener, AccountTypeAdapter.OnTypeClickListener
        , AccountAdapter.OnAccountSubscribeClickListener, AccountAdapter.OnAccountClickListener {

    @BindView(R.id.input_key)
    protected EditText searchKey;

    @BindView(R.id.left_list)
    protected RecyclerView leftListRecyclerView;

    @BindView(R.id.refresh_layout)
    protected CanRefreshLayout mRefreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView mRecyclerView;

    private AccountTypeAdapter typeAdapter;
    private AccountAdapter adapter;
    private boolean mIsLoading = false;
    private List<AccountTagBean> tagList = new ArrayList<>();
    private List<AccountBean> accountList = new ArrayList<>();
    private List<String> authorList = new ArrayList<>();
    private int currentTagIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        new TitleUtils(this).useAndSetTxTitle("关注更多");
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_more_account);
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void initView() {
        leftListRecyclerView.setItemAnimator(new DefaultItemAnimator());
        leftListRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setLoadMoreEnabled(false);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mRefreshLayout.autoRefresh();
        searchKey.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String str = searchKey.getText().toString().trim();
//                if (TextUtils.isEmpty(str)) {
//                    cleanBtn.setVisibility(View.GONE);
//                } else {
//                    cleanBtn.setVisibility(View.VISIBLE);
//                }
            }
        });
    }


    @Override
    public void onRefresh() {
        if (mIsLoading) {
            return;
        }
        accountList.clear();
        tagList.clear();
        currentTagIndex = 0;
        getData();
    }

    /**
     * 请求公众号
     */
    private void getData() {
        String token = "";
        String userId = "";
        if (null != UserManager.getInstance().getUser()) {
            token = UserManager.getInstance().getUser().getToken();
            userId = UserManager.getInstance().getUser().getUserId();
        }
        String nodeId = Cache.getInstance().getAccountNodeId();
        mIsLoading = true;
        Map<String, Object> param = new HashMap<>();
        param.put("siteNumber", Constances.SITE_ID);
        param.put("nodeId", nodeId);
        param.put("userId", userId);
        param.put("token", token);
        param.put("type", 3);
        NetUtils.getNetAdapter().getAccountTagList(getOwnerName(), param, new AbsListNetCallback<AccountTagBean>(null) {
            @Override
            public void onSuc(List<AccountTagBean> list) {
                if (ListUtils.isListValued(list)) {
                    tagList.addAll(list);
                    initTypeData();
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                toast("获取数据失败");

            }

            @Override
            public void onEnd() {
                onNetFinish();
                mIsLoading = false;
            }
        });

    }


    private void initTypeData() {
        if (ListUtils.isListValued(tagList)) {
            tagList.get(0).setSelected(true);
            if (null == adapter) {
                typeAdapter = new AccountTypeAdapter(this, this);
                leftListRecyclerView.setAdapter(typeAdapter);
                typeAdapter.setData(tagList);
            }else{
                typeAdapter.setData(tagList);
            }
            initData(tagList.get(0).getFollowedChildren());
        }


    }

    private void initData(List<AccountBean> newsItems) {
        if (null == adapter) {
            adapter = new AccountAdapter(this, newsItems, this, this);
            mRecyclerView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        } else {
            adapter.setData(newsItems);
        }

    }

    private synchronized void onNetFinish() {
        mIsLoading = false;
        mRefreshLayout.refreshComplete();
        mRefreshLayout.loadMoreComplete();
    }

    @Override
    public void OnTypeClick(int position) {

        for (int i = 0; i < tagList.size(); i++) {
            if (i == position) {
                tagList.get(i).setSelected(true);
            } else {
                tagList.get(i).setSelected(false);
            }
        }
        typeAdapter.setData(tagList);
        //TODO 选择类型
        currentTagIndex = position;
        accountList.clear();
//        if (ListUtils.isListValued(tagList.get(currentTagIndex).getFollowedChildren())) {
            adapter.setData(tagList.get(currentTagIndex).getFollowedChildren());
//        }
    }

    @Override
    public void OnAccountClick(AccountBean bean) {
        //TODO 点击公众号
        Intent intent = new Intent(this, AccountDetailActivity.class);
        intent.putExtra(AccountDetailActivity.ACCOUNT_ID, bean.getFollowedId());
        startActivityForResult(intent, 1);
    }

    @Override
    public void OnSubscribeClick(AccountBean bean) {
        //TODO 关注、取消关注公众号
        accountList = tagList.get(currentTagIndex).getFollowedChildren();
        for (int i = 0; i < accountList.size(); i++) {
            AccountBean da = (AccountBean) accountList.get(i);
            if (bean.getFollowedId().equalsIgnoreCase(da.getFollowedId())) {
                toAttentionClick(bean);
                break;
            }
        }
        setResult(RESULT_OK);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
            //TODO  搜索
            String key = searchKey.getText().toString().trim();
            if (TextUtils.isEmpty(key)) {
                toast("请输入关键词");
            } else {
                Intent intent = new Intent(this, AccountSearchActivity.class);
                intent.putExtra(AccountSearchActivity.INPUT_KEY, key);
                startActivityForResult(intent, 1);
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                mRefreshLayout.autoRefresh();
                setResult(RESULT_OK);
            }
        }
    }

    @OnClick(value = {R.id.title_top_back})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.title_top_back:
                onBackPressed();
                break;

        }
    }

    /**
     * 处理 关注或取消关注
     *
     * @param bean
     */
    private void toAttentionClick(final AccountBean bean) {
        if (bean.getFollowedStatus() == 1) {
            toUnAttentionAccount(bean.getFollowedId(), new BaseAccountActivity.OnAttentionListener() {
                @Override
                public void OnAttention(boolean isSuccess, long attentionedUserNums) {

                }

                @Override
                public void OnUnAttention(boolean isSuccess, long attentionedUserNums) {
                    accountList = tagList.get(currentTagIndex).getFollowedChildren();
                    for (int i = 0; i < accountList.size(); i++) {
                        AccountBean da = (AccountBean) accountList.get(i);
                        if (bean.getFollowedId().equalsIgnoreCase(da.getFollowedId())) {
                            ((AccountBean) accountList.get(i)).setFollowedStatus(0);
                            adapter.setData(accountList);
                            adapter.notifyDataSetChanged();
                            break;
                        }
                    }
                }
            });
        } else {
            toAttentionAccount(bean.getFollowedId(), new BaseAccountActivity.OnAttentionListener() {
                @Override
                public void OnAttention(boolean isSuccess, long attentionedUserNums) {
                    accountList = tagList.get(currentTagIndex).getFollowedChildren();
                    for (int i = 0; i < accountList.size(); i++) {
                        AccountBean da = (AccountBean) accountList.get(i);
                        if (bean.getFollowedId().equalsIgnoreCase(da.getFollowedId())) {
                            ((AccountBean) accountList.get(i)).setFollowedStatus(1);
                            adapter.setData(accountList);
                            adapter.notifyDataSetChanged();
                            break;
                        }
                    }
                }

                @Override
                public void OnUnAttention(boolean isSuccess, long attentionedUserNums) {

                }
            });
        }
    }

}
